package com.example.demo;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
public class UploadController {

    /** 绝对路径 **/
    private static String absolutePath = "";

    /** 静态目录 **/
    private static String staticDir = "/static";

    /** 文件存放的目录 **/
    private static String fileDir = "/img/";

    @GetMapping("/file_upload")
    public String uploadPage() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String create(@RequestPart MultipartFile file) throws IOException {
        // 第一次会创建文件夹
        createDirIfNotExists();
        String fileName = file.getOriginalFilename();
        String filePath = absolutePath + staticDir + fileDir + fileName;

        File dest = new File(filePath);
        Files.copy(file.getInputStream(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return "Upload file success : " + dest.getAbsolutePath();
    }

    @PostMapping("/uploads")
    @ResponseBody
    public String create(@RequestPart MultipartFile[] files) throws IOException {
        // 第一次会创建文件夹
        createDirIfNotExists();
        StringBuffer message = new StringBuffer();

        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String filePath = absolutePath + staticDir + fileDir + fileName;

            File dest = new File(filePath);
            Files.copy(file.getInputStream(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
            message.append("Upload file success : " + dest.getAbsolutePath()).append("<br>");
        }
        return message.toString();
    }

    @PostMapping("/wallpaper_uploads")
    @ResponseBody
    public String insertWallpaper(@RequestParam("files") MultipartFile[] files, 
            @RequestParam(value = "wallpaperName", required = false) String wallpaperName) throws IOException {
        // 第一次会创建文件夹
        createDirIfNotExists();
        StringBuffer message = new StringBuffer();
        message.append("Upload wallpaper name : " + wallpaperName).append("<br>");
        System.out.println(files);
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String filePath = absolutePath + staticDir + fileDir + fileName;

            File dest = new File(filePath);
            Files.copy(file.getInputStream(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
            message.append("Upload file success : " + dest.getAbsolutePath()).append("<br>");
        }
        return message.toString();
    }

    /**
     * 创建文件夹路径
     */
    private static void createDirIfNotExists() {
        if (!absolutePath.isEmpty()) {
            return;
        }

        // 获取跟目录
        File file = null;
        try {
            file = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            throw new RuntimeException("获取根目录失败，无法创建上传目录！");
        }
        if (!file.exists()) {
            file = new File("");
        }

        absolutePath = file.getAbsolutePath();

        File upload = new File(absolutePath, staticDir + fileDir);
        if (!upload.exists()) {
            upload.mkdirs();
        }
    }
}
